﻿using Authority.Model;
using Common.Library;
using Container.Library;
using Dapper.Library;
using Dapper.MsSql.Library;
using Encrypt.Library;
using Message.Library.Aliyun;
using Redis.Library;
using Dapper.Library.DataAccessSql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tool.Model;

namespace Authority.Logic
{
    /// <summary>
    /// 岗位功能管理逻辑
    /// </summary>
    public class SysOrganizationServiceImpl : ISysOrganizationService
    {
        #region 组织机构入驻操作逻辑
        /// <summary>
        /// 发送短信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> SendMessage(string parameters)
        {
            var resultInfo = new ResultJsonInfo<int>();
            if (parameters.IsNotNullOrEmpty())
            {
                using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
                {

                    var result = con.QuerySet<SysOrganizationEntity>()
                             .AndWhere(p => p.sPhone == parameters).Exists();
                    if (!result)
                    {
                        Random rd = new Random();
                        string message = rd.Next(10000, 99999).ToString();
                        RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                            .StringSet(ConstRedisKey.RedisSetteldCode + parameters, message, ConstRedisKey.SetteldCodeTimeOut);

                        var messageInfo = new MessageInfo<object>()
                        {
                            Mobile = parameters,
                            TemplateCodeKey = ConstAliyunSms.VerifyCodeTemplateKey,
                            Message = new
                            {
                                code = message
                            }
                        };
                        int sendResult = AliyunSendMsg.SendMessage<object>(messageInfo);
                        if (sendResult == 1)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Data = 1;
                        }
                        else
                        {
                            resultInfo.Msg = "发送失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败,手机号码已存在！";
                    }
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据Code获取操作信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> SettledApply(OrganizationSettledRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();

            string validateInfo = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                          .StringGet(ConstRedisKey.RedisSetteldCode + inputInfo.sPhone);

            if (validateInfo.IsNotNullOrEmpty())
            {
                if (inputInfo.sValidate == validateInfo)
                {
                    using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
                    {
                        var result = 0;
                        var sysOrganization = inputInfo.MapTo<SysOrganizationEntity>();
                        sysOrganization.gCode = GuidHelper.GetGuid();
                        sysOrganization.bIsEnabled = false;
                        sysOrganization.iStatus = (int)AuditStatus.Unaudited;
                        sysOrganization.iOrganizationCode = GetOrganizationNumber();
                        sysOrganization.sEncryptPassword = AESEncryptHelper.Encrypt(sysOrganization.sEncryptPassword);
                        result = con.CommandSet<SysOrganizationEntity>()
                                .IfNotExists(p => p.sName == sysOrganization.sName || p.sPhone == sysOrganization.sPhone)
                                .Insert(sysOrganization);

                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Data = result;
                            resultInfo.Msg = "申请成功，请等待平台审核，审核结果将发送到您的手机中！";
                        }
                        else
                        {
                            resultInfo.Msg = "操作失败,请检查公司名称或手机号码是否重复！";
                        }
                    }
                }
                else
                {
                    resultInfo.Msg = "验证码错误！";
                }
            }
            else
            {
                resultInfo.Msg = "验证码失效，请重新获取！";
            }
            return resultInfo;
        }


        //共享锁
        private static object NumberLock = new object();

        /// <summary>
        /// 获取组织机构编码
        /// </summary>
        /// <returns></returns>
        public static long GetOrganizationNumber()
        {
            StringBuilder sb = new StringBuilder();
            lock (NumberLock)
            {
                string newBase = DateTime.Now.ToString("yyMMddHHmmssfff");

                string organizationNoIndex = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                    .StringGet(ConstRedisKey.RedisOrganizationCode);

                if (organizationNoIndex.IsNullOrEmpty() || organizationNoIndex == "null")
                {
                    int index = NumeralHelper.Next(90) + 10;
                    RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                        .StringSet(ConstRedisKey.RedisOrganizationCode, index.ToString());
                    sb.Append(newBase + index);
                }
                else
                {
                    if (int.Parse(organizationNoIndex) < 99)
                    {
                        var index = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb).SetStringIncrement(ConstRedisKey.RedisOrganizationCode);
                        sb.Append(newBase + index);
                    }
                    else
                    {
                        var index = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb).StringSet(ConstRedisKey.RedisOrganizationCode, "10");
                        sb.Append(newBase + 10);
                    }
                }
            }
            return long.Parse(sb.ToString());
        }
        #endregion

        #region 组织机构管理界面逻辑

        /// <summary>
        /// 分页获取所有的可操作信息
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<SysOrganizationEntity>> LoadSysOrganizationList(ParametersInfo<string> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<SysOrganizationEntity>>();

            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = con.QuerySet<SysOrganizationEntity>().WithNoLock();
                if (inputInfo.parameters.IsNotNullOrEmpty())
                {
                    result = result.AndWhere(p => p.sName.Contains(inputInfo.parameters));
                }

                var listInfo = result.OrderBy(inputInfo.order == "asc" ? OrderByType.Asc : OrderByType.Desc, inputInfo.field)
                    .PageList(inputInfo.page, inputInfo.limit);

                if (listInfo.Data.IsNotNull())
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo.Data.ToList();
                    resultInfo.Count = listInfo.Total;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 获取所有的可操作信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<SelectListInfo>> LoadSysOrganizationAllList()
        {
            var resultInfo = new ResultJsonInfo<List<SelectListInfo>>();
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = con.QuerySet<SysOrganizationEntity>().WithNoLock().Multiple();

                if (result.Count > 0)
                {
                    var info = result.MapToList<SelectListInfo>();
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = info;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 修改信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> Save(OrganizationOperateRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;
                var sysOrganization = inputInfo.MapTo<SysOrganizationEntity>();
                con.Transaction(tran =>
                {
                    var existsOrganization = tran.QuerySet<SysOrganizationEntity>().AndWhere(p => p.gCode != sysOrganization.gCode && p.sName == sysOrganization.sName).Single();
                    if (existsOrganization.IsNull())
                    {
                        var organization = tran.QuerySet<SysOrganizationEntity>().AndWhere(p => p.gCode == sysOrganization.gCode).Single();

                        result = tran.CommandSet<SysOrganizationEntity>().AndWhere(p => p.gCode == sysOrganization.gCode)
                                           .UpdateByExp(p => new SysOrganizationEntity
                                           {
                                               sName = sysOrganization.sName,
                                               sAbbreviation = sysOrganization.sAbbreviation,
                                               sLeader = sysOrganization.sLeader,
                                               sPhone = sysOrganization.sPhone,
                                               sEmail = sysOrganization.sEmail,
                                               bIsEnabled = sysOrganization.bIsEnabled,
                                               sContent = sysOrganization.sContent
                                           });
                        if (sysOrganization.bIsEnabled == false)
                        {
                            tran.CommandSet<SysUserEntity>()
                            .AndWhere(p => p.iOrganizationCode == organization.iOrganizationCode)
                            .UpdateByExp(p => new SysUserEntity()
                            {
                                iState = (int)UserState.Frozen
                            });
                        }
                        else
                        {
                            tran.CommandSet<SysUserEntity>()
                            .AndWhere(p => p.iOrganizationCode == organization.iOrganizationCode)
                            .UpdateByExp(p => new SysUserEntity()
                            {
                                iState = (int)UserState.Normal
                            });
                        }
                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Data = result;
                            resultInfo.Msg = "操作成功！";
                        }
                        else
                        {
                            resultInfo.Msg = "操作失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败,请检查公司名称是否重复！";
                    }
                });
            }
            return resultInfo;
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="gCodeList"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> gCodeList)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;
                if (gCodeList.Count >= 0)
                {
                    var exists = con.QuerySet<SysUserPostEntity>().AndWhere(p => gCodeList.Contains(p.gPostCode)).Exists();
                    if (!exists)
                    {
                        result = con.CommandSet<SysPostEntity>()
                            .AndWhere(a => gCodeList.Contains(a.gCode))
                            .Delete();

                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Data = result;
                            resultInfo.Msg = "操作成功！";
                        }
                        else
                        {
                            resultInfo.Msg = "操作失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "选中岗位已被用户使用，无法删除！";
                    }
                }
                else
                {
                    resultInfo.Msg = "ID为空，操作失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 审核信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> AuditInfo(OrganizationAuditRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                con.Transaction(tran =>
                {
                    var organizationInfo = tran.QuerySet<SysOrganizationEntity>()
                                 .AndWhere(p => p.gCode == inputInfo.gCode).Single();

                    if (organizationInfo.IsNotNull())
                    {
                        //通过，就创建账号
                        if (inputInfo.iType == (int)AuditStatus.AuditPass)
                        {

                            #region 添加用户
                            SysUserEntity sysUser = new SysUserEntity();
                            sysUser.gCode = GuidHelper.GetGuid();
                            sysUser.sLoginName = organizationInfo.sPhone;
                            sysUser.sPhone = organizationInfo.sPhone;
                            sysUser.iOrganizationCode = organizationInfo.iOrganizationCode;
                            sysUser.sPassword = SecurityHelper.GetMD5Hash(AESEncryptHelper.Decrypt(organizationInfo.sEncryptPassword));
                            sysUser.sUserName = organizationInfo.sLeader;
                            sysUser.iSex = (int)SexType.Unknown;
                            sysUser.dCreateTime = DateTime.Now;
                            sysUser.bIsSuperAdmin = true;
                            sysUser.sLockScreenPsw = SecurityHelper.GetMD5Hash(AESEncryptHelper.Decrypt(organizationInfo.sEncryptPassword));
                            sysUser.iType = (int)UserType.Company;
                            var result = tran.CommandSet<SysUserEntity>()
                               .IfNotExists(p => p.sLoginName == sysUser.sLoginName)
                               .Insert(sysUser);

                            #endregion

                            var roleInfo = tran.QuerySet<SysRoleEntity>()
                                    .AndWhere(p => p.iType == (int)RoleType.Platform && p.bIsSuperAdmin == true).Single();
                            if (roleInfo != null)
                            {
                                #region 添加用户和角色关系信息

                                SysUserRoleEntity userRoleInfo = new SysUserRoleEntity();
                                userRoleInfo.gCode = GuidHelper.GetGuid();
                                userRoleInfo.gRoleCode = roleInfo.gCode;
                                userRoleInfo.gUserCode = sysUser.gCode;
                                tran.CommandSet<SysUserRoleEntity>().Insert(userRoleInfo);

                                #endregion

                                if (result > 0)
                                {
                                    organizationInfo.iStatus = (int)AuditStatus.AuditPass;
                                    organizationInfo.bIsEnabled = true;
                                    result = tran.CommandSet<SysOrganizationEntity>().Update(organizationInfo);
                                    if (result > 0)
                                    {
                                        resultInfo.Code = ActionCodes.Success;
                                        resultInfo.Data = result;
                                        resultInfo.Msg = "操作成功！";
                                    }
                                    else
                                    {
                                        resultInfo.Msg = "操作失败！";
                                    }
                                }
                                else
                                {
                                    resultInfo.Msg = $"账号{sysUser.sLoginName}已存在！";
                                }
                            }
                            else
                            {
                                resultInfo.Msg = "操作失败！";
                            }
                        }
                        else
                        {
                            organizationInfo.iStatus = (int)AuditStatus.AudiFailure;
                            int result = tran.CommandSet<SysOrganizationEntity>().Update(organizationInfo);
                            if (result > 0)
                            {
                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Data = result;
                                resultInfo.Msg = "操作成功！";
                            }
                            else
                            {
                                resultInfo.Msg = "操作失败！";
                            }
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败,无对应组织机构信息！";
                    }
                });
            }
            return resultInfo;
        }

        #endregion
    }
}
